package com.fiwizone.ultimateshoppinglist;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ItemEdit extends Activity {
	
	private static final String TAG = "UltimateShoppingList.ItemEdit";

	private EditText mTitleText;
	private EditText mCostText;
	private EditText mQuantityText;
    private Long mRowId;
    private Long mListId;
    
    private ShoppingData mDbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	Log.d(TAG, "onCreate()");
        super.onCreate(savedInstanceState);
        mDbHelper = new ShoppingData(this);
        mDbHelper.open();
        
        setContentView(R.layout.item_edit);
       
        mTitleText 	   = (EditText) findViewById(R.id.title);
        mCostText  	   = (EditText) findViewById(R.id.cost);
        mQuantityText  = (EditText) findViewById(R.id.quantity);
      
        Button confirmButton = (Button) findViewById(R.id.confirm);
        
        mRowId = mListId = null; 
        if (savedInstanceState != null) {
        	mRowId 	= savedInstanceState.getLong(ShoppingData.KEY_ROWID);
        	mListId = savedInstanceState.getLong(ShoppingData.KEY_LISTID);
        }       
        
		if (mRowId == null) {
			Bundle extras = getIntent().getExtras();            
			mRowId = extras != null ? extras.getLong(ShoppingData.KEY_ROWID) : null;
		}
		
		
		if (mListId == null) {
			Bundle extras = getIntent().getExtras();            
			mListId = extras != null ? extras.getLong(ShoppingData.KEY_LISTID) : null;
		}
		
		populateFields();
       
        confirmButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	if (saveState()) {            	
            		setResult(RESULT_OK);                
            		finish();
            	}
            }
          
        });
    }
    
    private void populateFields() {
        if (mRowId != null && mRowId != 0) {
            Cursor item = mDbHelper.fetchListItem(mRowId);
            startManagingCursor(item);
            
            mListId = item.getLong(
            		item.getColumnIndexOrThrow(ShoppingData.KEY_LISTID));
            mTitleText.setText(item.getString(
            		item.getColumnIndexOrThrow(ShoppingData.KEY_TITLE)));
            mCostText.setText(item.getString(
            		item.getColumnIndexOrThrow(ShoppingData.KEY_UNITCOST)));
            mQuantityText.setText(item.getString(
            		item.getColumnIndexOrThrow(ShoppingData.KEY_QUANTITY)));
        }
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	Log.d(TAG, "onSaveInstatnceState()");
        super.onSaveInstanceState(outState);        
        
        if (mRowId != null && mRowId != 0) {
        	outState.putLong(ShoppingData.KEY_ROWID, mRowId);
        }
        
        if (mListId != null && mListId != 0) {
        	outState.putLong(ShoppingData.KEY_LISTID, mListId);
        }
    }
    
    @Override
    protected void onPause() {
    	Log.d(TAG, "onPause()");
        super.onPause();        
    }
    
    @Override
    protected void onResume() {
    	Log.d(TAG, "onResume()");
        super.onResume();
        populateFields();
    }
    
    private boolean saveState() {
        String title = mTitleText.getText().toString();
        String cost = mCostText.getText().toString();
        String quantity = mQuantityText.getText().toString();
        Float fCost;
        Long lQuantity;
        
        // check to see if we have anything to save.
        if (null == title || "".equals(title)) {
        	Toast.makeText(this, "Title cannot be empty", Toast.LENGTH_SHORT).show();
        	return false;
        }
        
        // check to see if we have a valid value for cost
        if (null == cost || "".equals(cost)) {
        	fCost = 0.0F;
        }
        else {        
	        try {
	        	fCost = Float.valueOf(cost);
	        }
	        catch(NumberFormatException ex) {
	        	Toast.makeText(this, "Cost must be a valid amount", Toast.LENGTH_SHORT).show();
	        	return false;
	        }
        }
        
        // check to see if we have a valid value for quantity
        if (null == quantity || "".equals(quantity)) {
        	lQuantity = 1L;
        }
        else {        
	        try {
	        	lQuantity = Long.valueOf(quantity);
	        }
	        catch(NumberFormatException ex) {
	        	Toast.makeText(this, "Quanity must be a valid number", Toast.LENGTH_SHORT).show();
	        	return false;
	        }
        }

        if (mRowId == null || mRowId == 0) {
            long id = mDbHelper.createListItem(title, mListId, fCost, lQuantity);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateListItem(mRowId, title, fCost, lQuantity);
        }
        
        return true;
    }
}
